package com.uchedao.seller.manager;

import android.content.Context;

import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.uchedao.seller.config.Api;
import com.uchedao.seller.http.VolleyUtil;
import com.uchedao.seller.http.request.GetUrlRequest;
import com.uchedao.seller.http.response.ConfigDictResponse;

/**
 * 选项配置管理类
 * Created by hang on 2015/10/30.
 */
public class DictionaryManager {

    private static DictionaryManager instance;

    private static ConfigDictResponse.CarDict dictInfo;

    private DictionaryManager() {}

    public synchronized static DictionaryManager getInstance() {
        if(instance == null)
            instance = new DictionaryManager();
        return instance;
    }

    /**
     * 初始化字典数据
     */
    public static void getDictInfo(final Context context, final SyncDictCallback callback) {
        if(dictInfo != null) {
            if(callback != null)
                callback.syncCompleted(dictInfo);
            return;
        }

        GetUrlRequest req = new GetUrlRequest(Api.Action.CONFIG_DICT, new Response.Listener<JsonObject>() {
            @Override
            public void onResponse(JsonObject response) {
                ConfigDictResponse entity  = new Gson().fromJson(response, ConfigDictResponse.class);
                dictInfo = entity.car;

                if(callback != null)
                    callback.syncCompleted(dictInfo);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
            }
        });
        req.setTag("DictionaryManager");
        //设置超时时间 10 ＊ 1000
        req.setRetryPolicy(new DefaultRetryPolicy(10 * 1000, 1, 1.0f));
        VolleyUtil.getInstance().addToRequestQueue(req);
    }

    public interface SyncDictCallback {
        public void syncCompleted(ConfigDictResponse.CarDict dictEntity);
    }
}
